package com.yqya.springboot.shiro.practice.biz.impl;

import java.util.LinkedList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yqya.springboot.shiro.practice.biz.UserInfoBizService;
import com.yqya.springboot.shiro.practice.domain.UserInfo;
import com.yqya.springboot.shiro.practice.domain.UserRelateRoleInfo;
import com.yqya.springboot.shiro.practice.dto.UserInfoDTO;
import com.yqya.springboot.shiro.practice.service.UserInfoService;
import com.yqya.springboot.shiro.practice.service.UserRelateRoleInfoService;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;

/**
 * 用户信息业务服务接口实现类
 *
 * @author Kevin
 * @date 2019-07-28
 */
@Service
public class UserInfoBizServiceImpl implements UserInfoBizService {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserRelateRoleInfoService userRelateRoleInfoService;

    @Override
    public UserInfo save(UserInfoDTO dto) {
        String userName = dto.getName();
        String pwd = dto.getPwd();
        List<Long> roleIds = dto.getRoleIds();

        // 保存用户信息
        UserInfo item = new UserInfo();
        item.setName(userName);
        // 正常情况下密码都需要加盐加密，演示时使用明文
        item.setPwd(pwd);
        item.setCreateTime(DateUtil.date());
        userInfoService.save(item);

        if (CollUtil.isNotEmpty(roleIds)) {
            // 保存用户和角色的关系
            Long userId = item.getId();
            List<UserRelateRoleInfo> userRelateRoleList = new LinkedList<>();
            for (Long roleId : roleIds) {
                UserRelateRoleInfo userRelateRole = new UserRelateRoleInfo();
                userRelateRole.setUserId(userId);
                userRelateRole.setRoleId(roleId);
                userRelateRole.setCreateTime(DateUtil.date());
                userRelateRoleList.add(userRelateRole);
            }
            userRelateRoleInfoService.saveBatch(userRelateRoleList);
        }

        return item;
    }

}
